//
//  RAPComposeMenuView.swift
//  COPYCAT-Weibo
//
//  Created by 闫萌 on 1/3/16.
//  Copyright © 2016 RendezvousAuParadis. All rights reserved.
//

import UIKit
import pop

private let kButtonCount = 6
private let kColNumber = 3


class RAPComposeMenuView: UIImageView {
    
    
    private var buttonArray: [RAPComposeMenuButton] = [RAPComposeMenuButton]()
    // 注意，必须在创建menu view之后立即设置这个属性
    var hostController: UIViewController!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareBeforeUse()
    }
    
    private func prepareBeforeUse() {
        userInteractionEnabled = true
        
        addSubview(sloganView)
        sloganView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).offset(-200)
        }
        
        addSubButtons()
        
    }
    
    private func addSubButtons() {
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        let arr = NSArray(contentsOfFile: path!)
        
        // 间距大小
        let btnW: CGFloat = 100
        let btnH: CGFloat = 100
        let margin = (kScreenBounds.width - 3 * btnW) / 4
        let vMargin: CGFloat = 20
        
        // 排布六个按钮
        for idx in 0..<6 {
            
            guard let tmpArr = arr else {
                return
            }
            
            let title = tmpArr[idx]["title"] as! String
            let imageName = tmpArr[idx]["icon"] as! String
            
            let button = RAPComposeMenuButton(title: title, fontSize: 14, imageName: imageName, backgroundImageName: nil, target: self, action: "composeMenuButtonClicked:", textColor: UIColor.darkGrayColor())
            
            let col = idx % kColNumber
            let row = idx / kColNumber
            
            let btnX = CGFloat(col) * btnW + CGFloat(col + 1) * margin
            let btnY = CGFloat(row) * (btnH + vMargin) + kScreenBounds.height
            button.frame = CGRect(x: btnX, y: btnY, width: btnW, height: btnH)
            
            buttonArray.append(button)
            
            addSubview(button)
            
        }
        
    }
    
    @objc private func composeMenuButtonClicked(sender: RAPComposeMenuButton) {
        scaleButtons(sender)
        
    }
    
    private func scaleButtons(sender: RAPComposeMenuButton) {
        
            UIView.animateWithDuration(0.25, animations: { () -> Void in
                
                for btn in self.buttonArray {
                    if btn === sender { // 被点击的按钮放大
                        btn.transform = CGAffineTransformMakeScale(2, 2)
                    } else { // 其他按钮缩小
                        btn.transform = CGAffineTransformMakeScale(0.3, 0.3)
                    }
                    btn.alpha = 0.2
                }

            }, completion: { (_) -> Void in
                self.hostController.presentViewController(RAPMainNavigationController(rootViewController: RAPComposeViewController()), animated: true, completion: { () -> Void in
                    self.removeFromSuperview()
                })
            })

    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        // newSuperview 可能为空
        guard let sv = newSuperview else {
            return
        }
        image = UIImage.snapshotWithBlurEffectFromViewHierarchy(sv)
    }
    
//    POPSpringAnimation *anim = [POPSpringAnimation animationWithPropertyNamed:kPOPViewCenter];
//    
//    NSInteger height = CGRectGetHeight(self.view.bounds);
//    NSInteger width = CGRectGetWidth(self.view.bounds);
//    
//    CGFloat centerX = arc4random() % width;
//    CGFloat centerY = arc4random() % height;
//    
//    anim.toValue = [NSValue valueWithCGPoint:CGPointMake(centerX, centerY)];
//    anim.springBounciness = 16;
//    anim.springSpeed = 6;
//    [self.testView pop_addAnimation:anim forKey:@"center"];
    
    ///  在这个方法中实现动画效果
    override func didMoveToSuperview() {
        for (idx ,button) in buttonArray.enumerate() {
            // 按钮上升
            performAnimation(button, index: idx)

        }
    }
    
    
    private func performAnimation(button: UIButton, index: Int, goUP: Bool = true) {

        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        anim.toValue = NSValue(CGPoint: CGPoint(x: button.center.x, y: button.center.y + (goUP ? -kScreenBounds.height * 0.5 : kScreenBounds.height * 0.5)))
        anim.springSpeed = 6
        anim.springBounciness = 8
        anim.beginTime = CACurrentMediaTime() + CFTimeInterval(index) * 0.025
        button.pop_addAnimation(anim, forKey: "center")
    }
    
    
    
    // MARK: - 系统方法
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 触摸方法
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
//        removeFromSuperview()
        
        for (idx ,button) in buttonArray.enumerate().reverse() {
            // 按钮下降
            performAnimation(button, index: kButtonCount - idx, goUP: false)
        }
        
        // 从 super view 中移除
        /*
        模仿OC写一个 dispatch_after_snippet
        */
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            self.removeFromSuperview()
        }
        
    }

    // MARK: - 懒加载控件
    private lazy var sloganView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
}
